package main.Tests;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import main.FileVisitors.FileVisitorImpl.SimpleFileVisitor;
import main.Runnable.RunCount;

public class TestNoConcurrency extends Test {

    private SimpleFileVisitor fakeFileVisitor;

    public TestNoConcurrency(final String walkOnDrive, final int numberOfTests, final int maxThreadsPerTest, final String searchWithNoRegistry)
            throws IOException {
        this.walkOnDrive = walkOnDrive;
        this.numberOfTests = numberOfTests;
        this.maxThreadsPerTest = maxThreadsPerTest;
        this.searchWithNoRegistry = searchWithNoRegistry;
        printHeader(numberOfTests);
        runInitRootDirectories(walkOnDrive);
    }

    @Override
    public void runTest() throws InterruptedException, IOException {
        for (int j = 0; j < numberOfTests; j++) {
            print(String.format("----- Iteration: %d -----%n", j + 1));
            while (startActiveThreads <= maxThreadsPerTest) {
                fakeFileVisitor = new SimpleFileVisitor();
                long time = System.currentTimeMillis();
                final List<SimpleFileVisitor> list = initVisitors();
                runCountWithNoConcurrency(list);
                time = System.currentTimeMillis() - time;

                for(final SimpleFileVisitor visitor : list){
                    fakeFileVisitor.setFiles(fakeFileVisitor.getFiles() + visitor.getFiles());
                    fakeFileVisitor.setFolders(fakeFileVisitor.getFolders() + visitor.getFolders());
                    fakeFileVisitor.setTotalSize(fakeFileVisitor.getTotalSize() + visitor.getTotalSize());
                    fakeFileVisitor.getMatches().addAll(visitor.getMatches());
                }
                print(resultToString(fakeFileVisitor, time, walkOnDrive));
                startActiveThreads++;
            }
            startActiveThreads = 1;
        }
        printFooter();
    }

    private List<SimpleFileVisitor> initVisitors() {
        final List<SimpleFileVisitor> list = new ArrayList<SimpleFileVisitor>();
        for (int i = 0; i < rootDirectories.getRootDirectories().size(); i++) {
            list.add(new SimpleFileVisitor(searchWithNoRegistry));
        }
        return list;
    }

    private void runCountWithNoConcurrency(final List<SimpleFileVisitor> visitors) throws InterruptedException {
        final ExecutorService service = Executors.newFixedThreadPool(startActiveThreads);
        int i = 0;
        for (final Path path : rootDirectories.getRootDirectories()) {
            final RunCount runCount = new RunCount(path, visitors.get(i++));
            service.execute(runCount);
        }
        serviceShutdown(service);
    }

}
